package com.farmer.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmer.common.entity.Order;
import com.farmer.common.entity.OrderItem;
import com.farmer.common.result.Result;
import com.farmer.order.dto.CreateOrderDTO;
import com.farmer.order.mapper.OrderItemMapper;
import com.farmer.order.mapper.OrderMapper;
import com.farmer.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单服务实现类
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    // @Autowired
    // private ProductFeignClient productFeignClient;

    @Override
    @Transactional
    public Result<?> createOrder(CreateOrderDTO createOrderDTO) {
        try {
            // 生成订单号
            String orderNo = generateOrderNo();

            // 先计算订单总金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (CreateOrderDTO.OrderItemDTO item : createOrderDTO.getItems()) {
                // 模拟商品价格（后续应调用商品服务获取）
                BigDecimal price = new BigDecimal("10.00");
                totalAmount = totalAmount.add(price.multiply(new BigDecimal(item.getQuantity())));
            }

            // 创建订单主表并设置 totalAmount
            Order order = new Order();
            order.setOrderNo(orderNo);
            order.setUserId(createOrderDTO.getUserId());
            order.setReceiverName(createOrderDTO.getReceiverName());
            order.setReceiverPhone(createOrderDTO.getReceiverPhone());
            order.setReceiverAddress(createOrderDTO.getReceiverAddress());
            order.setShippingFee(createOrderDTO.getShippingFee() != null ? createOrderDTO.getShippingFee() : BigDecimal.ZERO);
            order.setOrderStatus("PENDING");
            order.setRemark(createOrderDTO.getRemark());
            order.setTotalAmount(totalAmount.add(order.getShippingFee())); // 先赋值 total_amount

            // 插入订单主表
            int orderResult = orderMapper.insert(order);
            if (orderResult <= 0) {
                return Result.error("创建订单失败");
            }

            // 处理订单明细
            for (CreateOrderDTO.OrderItemDTO itemDTO : createOrderDTO.getItems()) {
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(order.getId());
                orderItem.setProductId(itemDTO.getProductId());
                orderItem.setProductName("商品名称"); // 从商品服务获取
                orderItem.setPrice(new BigDecimal("10.00")); // 从商品服务获取
                orderItem.setQuantity(itemDTO.getQuantity());
                orderItem.setAmount(orderItem.getPrice().multiply(new BigDecimal(itemDTO.getQuantity())));

                int itemResult = orderItemMapper.insert(orderItem);
                if (itemResult <= 0) {
                    throw new RuntimeException("创建订单明细失败");
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("orderId", order.getId());
            result.put("orderNo", orderNo);
            result.put("totalAmount", order.getTotalAmount());

            log.info("创建订单成功，订单号：{}", orderNo);
            return Result.success("创建订单成功", result);

        } catch (Exception e) {
            log.error("创建订单失败：{}", e.getMessage(), e);
            return Result.error("创建订单失败：" + e.getMessage());
        }
    }
//    public Result<?> createOrder(CreateOrderDTO createOrderDTO) {
//        try {
//            // 生成订单号
//            String orderNo = generateOrderNo();
//
//            // 计算订单总金额
//            BigDecimal totalAmount = BigDecimal.ZERO;
//
//            // 创建订单主表
//            Order order = new Order();
//            order.setOrderNo(orderNo);
//            order.setUserId(createOrderDTO.getUserId());
//            order.setReceiverName(createOrderDTO.getReceiverName());
//            order.setReceiverPhone(createOrderDTO.getReceiverPhone());
//            order.setReceiverAddress(createOrderDTO.getReceiverAddress());
//            order.setShippingFee(createOrderDTO.getShippingFee() != null ? createOrderDTO.getShippingFee() : BigDecimal.ZERO);
//            order.setOrderStatus("PENDING");
//            order.setRemark(createOrderDTO.getRemark());
//
//            // 先插入订单主表获取订单ID
//            int orderResult = orderMapper.insert(order);
//            if (orderResult <= 0) {
//                return Result.error("创建订单失败");
//            }
//
//            // 处理订单明细
//            for (CreateOrderDTO.OrderItemDTO itemDTO : createOrderDTO.getItems()) {
//                // 这里应该调用商品服务获取商品信息和检查库存
//                // 为了简化，这里暂时跳过远程调用
//
//                OrderItem orderItem = new OrderItem();
//                orderItem.setOrderId(order.getId());
//                orderItem.setProductId(itemDTO.getProductId());
//                orderItem.setProductName("商品名称"); // 从商品服务获取
//                orderItem.setPrice(new BigDecimal("10.00")); // 从商品服务获取
//                orderItem.setQuantity(itemDTO.getQuantity());
//                orderItem.setAmount(orderItem.getPrice().multiply(new BigDecimal(itemDTO.getQuantity())));
//
//                totalAmount = totalAmount.add(orderItem.getAmount());
//
//                int itemResult = orderItemMapper.insert(orderItem);
//                if (itemResult <= 0) {
//                    throw new RuntimeException("创建订单明细失败");
//                }
//            }
//
//            // 更新订单总金额
//            order.setTotalAmount(totalAmount.add(order.getShippingFee()));
//            orderMapper.updateById(order);
//
//            Map<String, Object> result = new HashMap<>();
//            result.put("orderId", order.getId());
//            result.put("orderNo", orderNo);
//            result.put("totalAmount", order.getTotalAmount());
//
//            log.info("创建订单成功，订单号：{}", orderNo);
//            return Result.success("创建订单成功", result);
//
//        } catch (Exception e) {
//            log.error("创建订单失败：{}", e.getMessage(), e);
//            return Result.error("创建订单失败：" + e.getMessage());
//        }
//    }

    @Override
    public Result<?> getOrderById(Long orderId, Long userId) {
        try {
            if (orderId == null) {
                return Result.error("订单ID不能为空");
            }

            Order order = orderMapper.selectById(orderId);
            if (order == null) {
                return Result.error("订单不存在");
            }

            // 权限验证：只能查看自己的订单
            if (userId != null && !order.getUserId().equals(userId)) {
                return Result.error("无权查看此订单");
            }

            // 查询订单明细
            QueryWrapper<OrderItem> itemQuery = new QueryWrapper<>();
            itemQuery.eq("order_id", orderId);
            List<OrderItem> orderItems = orderItemMapper.selectList(itemQuery);

            Map<String, Object> result = new HashMap<>();
            result.put("order", order);
            result.put("items", orderItems);

            return Result.success("获取订单详情成功", result);
        } catch (Exception e) {
            log.error("获取订单详情失败：{}", e.getMessage(), e);
            return Result.error("获取订单详情失败");
        }
    }

    @Override
    public Result<?> getUserOrderList(Long userId, Integer pageNum, Integer pageSize, String status) {
        try {
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }

            Page<Order> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);

            if (StringUtils.hasText(status)) {
                queryWrapper.eq("order_status", status);
            }

            queryWrapper.orderByDesc("create_time");

            Page<Order> orderPage = orderMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", orderPage.getRecords());
            result.put("total", orderPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取订单列表成功", result);
        } catch (Exception e) {
            log.error("获取用户订单列表失败：{}", e.getMessage(), e);
            return Result.error("获取订单列表失败");
        }
    }

    @Override
    public Result<?> getAllOrderList(Integer pageNum, Integer pageSize, String status, String keyword) {
        try {
            Page<Order> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();

            if (StringUtils.hasText(status)) {
                queryWrapper.eq("order_status", status);
            }

            if (StringUtils.hasText(keyword)) {
                queryWrapper.and(wrapper -> wrapper
                    .like("order_no", keyword)
                    .or()
                    .like("receiver_name", keyword)
                    .or()
                    .like("receiver_phone", keyword)
                );
            }

            queryWrapper.orderByDesc("create_time");

            Page<Order> orderPage = orderMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", orderPage.getRecords());
            result.put("total", orderPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取订单列表成功", result);
        } catch (Exception e) {
            log.error("获取所有订单列表失败：{}", e.getMessage(), e);
            return Result.error("获取订单列表失败");
        }
    }

    @Override
    public Result<?> updateOrderStatus(Long orderId, String status) {
        try {
            if (orderId == null || !StringUtils.hasText(status)) {
                return Result.error("参数不能为空");
            }

            Order order = orderMapper.selectById(orderId);
            if (order == null) {
                return Result.error("订单不存在");
            }

            order.setOrderStatus(status);
            if ("PAID".equals(status)) {
                order.setPaymentTime(LocalDateTime.now());
            }

            int result = orderMapper.updateById(order);
            if (result > 0) {
                log.info("更新订单状态成功，订单号：{}，状态：{}", order.getOrderNo(), status);
                return Result.success("更新订单状态成功");
            } else {
                return Result.error("更新订单状态失败");
            }
        } catch (Exception e) {
            log.error("更新订单状态失败：{}", e.getMessage(), e);
            return Result.error("更新订单状态失败");
        }
    }

    @Override
    public Result<?> cancelOrder(Long orderId, Long userId) {
        try {
            if (orderId == null) {
                return Result.error("订单ID不能为空");
            }

            Order order = orderMapper.selectById(orderId);
            if (order == null) {
                return Result.error("订单不存在");
            }

            // 权限验证
            if (userId != null && !order.getUserId().equals(userId)) {
                return Result.error("无权操作此订单");
            }

            // 只有待付款状态的订单可以取消
            if (!"PENDING".equals(order.getOrderStatus())) {
                return Result.error("只有待付款订单可以取消");
            }

            order.setOrderStatus("CANCELLED");
            int result = orderMapper.updateById(order);
            
            if (result > 0) {
                log.info("取消订单成功，订单号：{}", order.getOrderNo());
                return Result.success("取消订单成功");
            } else {
                return Result.error("取消订单失败");
            }
        } catch (Exception e) {
            log.error("取消订单失败：{}", e.getMessage(), e);
            return Result.error("取消订单失败");
        }
    }

    @Override
    public Result<?> confirmReceive(Long orderId, Long userId) {
        try {
            if (orderId == null) {
                return Result.error("订单ID不能为空");
            }

            Order order = orderMapper.selectById(orderId);
            if (order == null) {
                return Result.error("订单不存在");
            }

            // 权限验证
            if (userId != null && !order.getUserId().equals(userId)) {
                return Result.error("无权操作此订单");
            }

            // 只有已发货状态的订单可以确认收货
            if (!"SHIPPED".equals(order.getOrderStatus())) {
                return Result.error("只有已发货订单可以确认收货");
            }

            order.setOrderStatus("DELIVERED");
            int result = orderMapper.updateById(order);
            
            if (result > 0) {
                log.info("确认收货成功，订单号：{}", order.getOrderNo());
                return Result.success("确认收货成功");
            } else {
                return Result.error("确认收货失败");
            }
        } catch (Exception e) {
            log.error("确认收货失败：{}", e.getMessage(), e);
            return Result.error("确认收货失败");
        }
    }

    @Override
    public Result<?> getOrderStatistics() {
        try {
            // 统计各状态订单数量
            Map<String, Long> statusCount = new HashMap<>();
            
            // 分别统计各状态的订单数量
            String[] statuses = {"PENDING", "PAID", "SHIPPED", "COMPLETED", "CANCELLED"};
            for (String status : statuses) {
                QueryWrapper<Order> statusQuery = new QueryWrapper<>();
                statusQuery.eq("order_status", status);
                Long count = orderMapper.selectCount(statusQuery);
                statusCount.put(status, count);
            }

            // 计算总订单数
            Long totalOrders = orderMapper.selectCount(null);
            
            // 计算已完成订单的总金额
            QueryWrapper<Order> completedQuery = new QueryWrapper<>();
            completedQuery.eq("order_status", "COMPLETED");
            List<Order> completedOrders = orderMapper.selectList(completedQuery);
            
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (Order order : completedOrders) {
                if (order.getTotalAmount() != null) {
                    totalAmount = totalAmount.add(order.getTotalAmount());
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("statusCount", statusCount);
            result.put("totalOrders", totalOrders);
            result.put("totalAmount", totalAmount);

            log.info("订单统计成功：总订单数={}, 已完成订单金额={}", totalOrders, totalAmount);
            return Result.success("获取订单统计成功", result);
        } catch (Exception e) {
            log.error("获取订单统计失败：{}", e.getMessage(), e);
            return Result.error("获取订单统计失败");
        }
    }

    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.valueOf((int) (Math.random() * 9000) + 1000);
        return "FO" + timestamp + random;
    }
} 